package com.hzx.demo.helper;

import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.util.Log;

import java.io.IOException;
import java.util.List;

/**
 * 模仿Camera2的录像功能模块
 * 提供了录像的功能
 * 起名Module仅仅是出于对原作者的尊重, 就是个辅助类
 *
 * Note: 代码中的前置摄像头与横屏模式代码没有编写, 使用时可能会抛出异常,
 *        如有需要, 请根据需要添加所需的逻辑控制
 * Created by ldkxingzhe on 2016/6/28.
 */
public class VideoModule extends CameraModule{
    @SuppressWarnings("unused")
    private static final String TAG = "VideoModule";

    private MediaRecorder mMediaRecorder;

    /**
     * 开始录制视频,
     * called after openCamera;
     * @param filePath
     */
    public void startRecorder(String filePath){
        if(mCamera == null){
            throw new IllegalStateException("startRecorder must called after openCamera");
        }
        makeSureFileFine(filePath);
        try {
            initializeRecorder(filePath);
            mMediaRecorder.start();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    @Override
    protected void diyCameraParameters(Camera.Parameters parameters) {
        List<String> supportFocusMode = parameters.getSupportedFocusModes();
        if(supportFocusMode.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)){
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        }else{
            Log.e(TAG, "In function openCamera, and not support continuous video");
        }
    }

    private void initializeRecorder(String filePath) throws IOException {
        if(mMediaRecorder != null) stopRecorderAndReleaseMediaRecorder();
        mMediaRecorder = new MediaRecorder();
        mCamera.unlock();
        mMediaRecorder.setCamera(mCamera);
        CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
        mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
        mMediaRecorder.setVideoEncodingBitRate(profile.videoFrameWidth * 1024);

        mMediaRecorder.setOutputFile(filePath);
        // FIXME: 2016/6/28 添加代码控制方向
        mMediaRecorder.setOrientationHint(90);
        mMediaRecorder.prepare();
    }

    /**
     * 停止录制, 并且释放MediaRecorder资源
     */
    public void stopRecorderAndReleaseMediaRecorder(){
        if(mMediaRecorder == null) return;
        mMediaRecorder.stop();
        mMediaRecorder.release();
        mMediaRecorder = null;
    }

}
